package com.chuanyang.driverh.mainorder;


import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainorder.adapter.UpPicAdapter;
import com.chuanyang.driverh.mainother.LookPicActivity;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PermissoinUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshActivityEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshOrderData;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;

public class SureUnLoadOverActivity extends BaseTitleActivity implements AdapterView.OnItemClickListener {

    private static final int REQUEST_IMAGE = 2;
    private ArrayList<String> mSelectPath;
    private GridView gv_pic;
    private int maxNum = 8;
    private UpPicAdapter adapter;
    private Intent intent;
    private boolean isorder;
    private ArrayList<File> compressfiles;
    private int id;
    private TextView tv_sureloadover_sure;
    private TextView tv_sureloadover_desribe;
    private EditText et_remark;
    private boolean personalOrder;
    private boolean ifChangeStatus=true;


    @Override
    protected int getContentResId(){
        return R.layout.order_act_sureunloadover;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        getTitleTextView().setText("确认卸货");
        gv_pic = (GridView) findViewById(R.id.gv_pic);
        tv_sureloadover_sure = (TextView) findViewById(R.id.tv_sureloadover_sure);
        tv_sureloadover_desribe = (TextView) findViewById(R.id.tv_sureloadover_desribe);
        et_remark = (EditText) findViewById(R.id.et_remark);
    }

    @Override
    protected void initData() {
        setBackImg();
        Intent intent = getIntent();
        compressfiles = new ArrayList();
        if (intent.getIntExtra("orederId", -1) != -1) {
            isorder = true;
            id = intent.getIntExtra("orederId", -1);
            //表示是个人的订单
            personalOrder = intent.getBooleanExtra("personalOrder", false);
        } else {
            isorder = false;
            id = intent.getIntExtra("waybillId", -1);
        }

        if (getIntent().getIntExtra("maxNum",0)>0){
            maxNum=getIntent().getIntExtra("maxNum",0);
        }
        ifChangeStatus=intent.getBooleanExtra("ifChangeStatus",true);
        if (!ifChangeStatus){
            et_remark.setVisibility(View.GONE);
        }else {
            et_remark.setVisibility(View.VISIBLE);
        }

        mSelectPath = new ArrayList();
        adapter = new UpPicAdapter(this, mSelectPath, maxNum);
        gv_pic.setAdapter(adapter);
        tv_sureloadover_desribe.setText("请上传1-"+maxNum+"张卸货照片");

        if (!ifChangeStatus){
            pickImage();
        }
    }

    @Override
    protected void initListener() {
        gv_pic.setOnItemClickListener(this);
        tv_sureloadover_sure.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_sureloadover_sure:
                if (mSelectPath.size() > 0) {
                    //防止短时间重复点击。
                    tv_sureloadover_sure.setEnabled(false);
                    DialogUtil.showLoadingDialog(activityContext,"提交中...");
                    compressImages();

                }else {
                    PrintUtil.toast(activityContext,"请上传1-8张收货照片");
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (position == 0 && mSelectPath.size() == 0) {
            pickImage();
        } else if (position == mSelectPath.size() && mSelectPath.size() < maxNum)//最后一张图是添加时
        {
            pickImage();
        } else {
            intent = new Intent(SureUnLoadOverActivity.this, LookPicActivity.class);
            intent.putStringArrayListExtra("imagepaths", mSelectPath);
            intent.putExtra("index", position);
            startActivityForResult(intent, 1);
        }
    }


    private void pickImage() {
        boolean flag= PermissoinUtil.checkAndRequestPermissions(activityContext,new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE});
        if (flag){
            boolean showCamera = true;
            MultiImageSelector selector = MultiImageSelector.create(SureUnLoadOverActivity.this);
            selector.showCamera(showCamera);
            selector.count(maxNum);
            selector.multi();
            selector.origin(mSelectPath);
            selector.start(SureUnLoadOverActivity.this, REQUEST_IMAGE);

        }else{
            PrintUtil.toast(activityContext,"请给应用添加存储权限");
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath.clear();
                mSelectPath.addAll(data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT));
                adapter.notifyDataSetChanged();

            }

        } else if (resultCode == 1)//此时代表删除图片
        {
            int deleteIndex = data.getIntExtra("position", 0);
            mSelectPath.remove(deleteIndex);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 多图上传时压缩图片的方法
     */
    private void compressImages() {
        compressfiles.clear();
        if (mSelectPath.size() > 0) {
            for (String path : mSelectPath) {
                File photo = BitmapUtil.compressImage(path, this);
                compressfiles.add(photo);
            }
        }



        if (ifChangeStatus){//需要传运单或订单状态
            if (personalOrder) {
                updateOrderUnload(id);
            }
            else {
                updateWaybillUnload(id);
            }
        }else {
            uploadWaybillImagess(id);
        }


    }


    /**
     * 卸货完成和代替货主收货接口 (个人订单时)
     */
    private void updateOrderUnload(final int id) {
        DialogUtil.showLoadingDialog(activityContext,"提交中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", id + "");
        params.put("orderStatus", "6");

        MyHttpUtil.updateOrderUnload(activityContext,compressfiles,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                tv_sureloadover_sure.setEnabled(true);
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    for (File file : compressfiles) {
                        file.delete();
                    }
                    if (isorder) {
                        EventBus.getDefault().post(new RefleshOrderData(1));
                    } else if (!isorder) {
                        EventBus.getDefault().post(new RefleshOrderData(2));
                    }
                    EventBus.getDefault().post(new RefleshFragEvent(3));

                    PrintUtil.toast(activityContext, "卸货成功！");
                    finish();
                }else {
                    PrintUtil.toast(activityContext,result.getMsg());
                    tv_sureloadover_sure.setEnabled(true);
                }
            }
        });

    }

    /**
     * 车 主确认卸货  （传入订单id或者运单id）
     */
    private void updateWaybillUnload(final int id) {
        DialogUtil.showLoadingDialog(activityContext,"提交中...");
        Map<String,String> params=new HashMap<String, String>();
        if (isorder) {
            params.put("orderId", id + "");
        } else {
            params.put("waybillId", id + "");
        }
        params.put("waybillStatus", "6");
        params.put("updateWaybillUnload",et_remark.getText().toString().trim());
        MyHttpUtil.updateWaybillUnload(activityContext,compressfiles,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                tv_sureloadover_sure.setEnabled(true);
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                        for (File file : compressfiles) {
                            file.delete();
                        }
                        if (isorder) {
                            EventBus.getDefault().post(new RefleshOrderData(1));
                        } else if (!isorder) {
                            EventBus.getDefault().post(new RefleshOrderData(2));

                        }
                        PrintUtil.toast(activityContext,"卸货成功！");
                        EventBusUtil.postEvent(new RefleshFragEvent(3));
                        EventBusUtil.postEvent(new RefleshActivityEvent(0));
                        finish();

                }else{
                    tv_sureloadover_sure.setEnabled(true);
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });


    }



    /**
     * 上传照片
     */
    private void uploadWaybillImagess(final int id) {
        DialogUtil.showLoadingDialog(activityContext,"提交中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("waybillId", id + "");
        MyHttpUtil.uploadWaybillImagess(activityContext,compressfiles,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
                tv_sureloadover_sure.setEnabled(true);
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    for (File file : compressfiles) {
                        file.delete();
                    }
                    if (isorder) {
                        EventBus.getDefault().post(new RefleshOrderData(1));
                    } else if (!isorder) {
                        EventBus.getDefault().post(new RefleshOrderData(2));
                    }
                    PrintUtil.toast(activityContext,"照片上传成功！");
                    EventBusUtil.postEvent(new RefleshFragEvent(3));
                    EventBusUtil.postEvent(new RefleshActivityEvent(0));
                    finish();
                }else{
                    tv_sureloadover_sure.setEnabled(true);
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });


    }

}
